import type { RouteRecordRaw, RouteLocationNormalized, RouteRecordNormalized } from 'vue-router';
import type { App } from 'vue';

import { createRouter, createWebHashHistory } from 'vue-router';
import { basicRoutes } from './routes';
import { setupRouterGuard } from './guard';

// 白名单应该包含基本静态路由
const WHITE_NAME_LIST: string[] = [];
const getRouteNames = (array: any[]) =>
	array.forEach(item => {
		WHITE_NAME_LIST.push(item.name);
		getRouteNames(item.children || []);
	});
getRouteNames(basicRoutes);

export const router = createRouter({
	history: createWebHashHistory(import.meta.env.VITE_PUBLIC_PATH),
	routes: basicRoutes as unknown as RouteRecordRaw[],
	strict: true,
	scrollBehavior: () => ({ left: 0, top: 0 }),
});

// reset router
export function resetRouter() {
	router.getRoutes().forEach(route => {
		const { name } = route;
		if (name && !WHITE_NAME_LIST.includes(name as string)) {
			router.hasRoute(name) && router.removeRoute(name);
		}
	});
}

export function getRawRoute(route: RouteLocationNormalized): RouteLocationNormalized {
	if (!route) return route;
	const { matched, ...opt } = route;
	return {
		...opt,
		matched: (matched
			? matched.map(item => ({
					meta: item.meta,
					name: item.name,
					path: item.path,
			  }))
			: undefined) as RouteRecordNormalized[],
	};
}

export function setupRouter(app: App) {
	app.use(router);
	setupRouterGuard(router);
}
